package com.ailesson.user.service.impl;

import com.ailesson.common.except.GlobalErrorCodeConstants;
import com.ailesson.common.except.ServiceException;
import com.ailesson.user.config.WechatProperties;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;

import com.ailesson.user.mapper.WxpMenuMapper;
import com.ailesson.user.entity.WxpMenuEntity;
import com.ailesson.user.service.WxpMenuService;
import com.ailesson.user.model.req.WxpMenuQueryReq;
import com.ailesson.user.model.req.WxpMenuReq;
import com.ailesson.user.model.reply.WxpMenuReply;
import com.ailesson.common.reply.PageResult;
import cn.hutool.core.collection.CollectionUtil;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class WxpMenuServiceImpl extends ServiceImpl<WxpMenuMapper, WxpMenuEntity> implements WxpMenuService {

    private static final Long PARENTID = 0L;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WechatProperties wechatProperties;

    @Override
    public PageResult queryPage(WxpMenuQueryReq params) {
       Page pageTmp = Page.of(params.getPageNo(),params.getPageSize());
       IPage<WxpMenuEntity> page = this.page(
               pageTmp,
               new LambdaQueryWrapper<WxpMenuEntity>().orderByDesc(WxpMenuEntity::getId)
       );
       List<WxpMenuReply> replyList = Collections.EMPTY_LIST;
       if (CollectionUtil.isNotEmpty(page.getRecords())){
           replyList = page.getRecords().stream().map(x -> {
               WxpMenuReply reply = new WxpMenuReply();
               BeanUtils.copyProperties(x, reply);
               return reply;
           }).collect(Collectors.toList());
       }
       return new PageResult<>(replyList,page.getTotal());
    }

    @Override
    public WxpMenuReply info(Long id) {
        WxpMenuEntity entity = this.getById(id);
        if (entity != null){
            WxpMenuReply reply = new WxpMenuReply();
            BeanUtils.copyProperties(entity, reply);
            return reply;
        }
        return null;
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    @Override
    public void update(WxpMenuReq wxpMenu) {
        if (wxpMenu.getId() == null || wxpMenu.getId() <= 0){
            throw new ServiceException(GlobalErrorCodeConstants.ID_EMPTY_ERROR);
        }
        WxpMenuEntity entity = this.getById(wxpMenu.getId());
        if (entity == null){
            throw new ServiceException(GlobalErrorCodeConstants.NOT_EXISTS_ERROR);
        }
        BeanUtils.copyProperties(wxpMenu, entity);
        this.updateById(entity);
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    @Override
    public Long add(WxpMenuReq wxpMenu) {
        wxpMenu.setId(null);
        WxpMenuEntity entity = new WxpMenuEntity();
        BeanUtils.copyProperties(wxpMenu, entity);
        this.save(entity);
        return entity.getId();
    }

    @Override
    public String getAccessToken() {
        try {
            return wxMpService.getAccessToken();
        } catch (WxErrorException e) {
            throw new ServiceException(e.getError().getErrorCode(),e.getError().getErrorMsg());
        }
    }

    @Override
    public List<WxpMenuReply> queryAll() {
        List<WxpMenuEntity> list = this.list(new LambdaQueryWrapper<>());
        List<WxpMenuEntity> oneLevels = list.stream().filter(x -> x.getParentId() == PARENTID.longValue()).collect(Collectors.toList());
        List<WxpMenuReply> menuReplies = oneLevels.stream().map(x -> {
            WxpMenuReply reply = new WxpMenuReply();
            BeanUtils.copyProperties(x, reply);
            List<WxpMenuEntity> secondLevels = list.stream().filter(y -> y.getParentId() == x.getId().longValue()).collect(Collectors.toList());
            List<WxpMenuReply> replyList = secondLevels.stream().map(z -> {
                WxpMenuReply tmp = new WxpMenuReply();
                BeanUtils.copyProperties(z, tmp);
                return tmp;
            }).collect(Collectors.toList());
            reply.setChildren(replyList);
            return reply;
        }).collect(Collectors.toList());
        return menuReplies;
    }

    @Override
    public List<WxpMenuReply> queryOneLevel() {
        List<WxpMenuEntity> list = this.list(new LambdaQueryWrapper<WxpMenuEntity>().eq(WxpMenuEntity::getParentId,PARENTID));
        List<WxpMenuReply> menuReplies = list.stream().map(x -> {
            WxpMenuReply reply = new WxpMenuReply();
            BeanUtils.copyProperties(x, reply);
            return reply;
        }).collect(Collectors.toList());
        return menuReplies;
    }

    @Override
    public void removeMenu() {
        try {
            wxMpService.getMenuService().menuDelete();
        } catch (WxErrorException e) {
            throw new ServiceException(e.getError().getErrorCode(),e.getError().getErrorMsg());
        }
    }

    @Override
    public void syncMenu() {
        JSONArray buttonList = new JSONArray();
        for (WxpMenuReply reply : this.queryAll()) {
            JSONObject one = new JSONObject();
            one.put("name",reply.getName());
            JSONArray subList = new JSONArray();
            for (WxpMenuReply sub : reply.getChildren()){
                JSONObject subBut = new JSONObject();
                subBut.put("type",sub.getType());
                subBut.put("name", sub.getName());
                if ("view".equals(sub.getType())){
                    subBut.put("url", wechatProperties.getMpUrlProfix()+sub.getUrl());
                }else {
                    subBut.put("key",sub.getMeunKey());
                }
                subList.add(subBut);
            }
            one.put("sub_button",subList);
            buttonList.add(one);
        }
        //封装最外层button部分
        JSONObject button = new JSONObject();
        button.put("button",buttonList);
        try {
            wxMpService.getMenuService().menuCreate(button.toJSONString());
        } catch (WxErrorException e) {
            throw new ServiceException(e.getError().getErrorCode(),e.getError().getErrorMsg());
        }
    }
}